<template>
  <div>
    <!--    <div>
      <p>demo3</p>
    </div>-->
    <div ref="container" id="container"></div>
  </div>
</template>

<script setup>
import * as THREE from "three";
import { onMounted, ref, onBeforeUnmount, reactive, onUnmounted } from "vue";
import { MMDLoader } from "three/examples/jsm/loaders/MMDLoader.js";

const container = ref(null);
let scene, camera, renderer;

// 相机位置的响应式数据
const cameraPosition = reactive({
  x: 0,
  y: 0,
  z: 75,
});

const useKeyboardEvent = () => {
  const handleKeyDown = (event) => {
    switch (event.key) {
      case "s": {
        cameraPosition.y += 10;
        break;
      }
      case "w": {
        cameraPosition.y -= 10;
        break;
      }
      case "a": {
        cameraPosition.x += 10;
        break;
      }
      case "d": {
        cameraPosition.x -= 10;
        break;
      }
    }
    camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z);
  };

  const handleKeyUp = (event) => {
    // console.log(`Key up: ${event.key}`);
  };

  onMounted(() => {
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);
  });

  onUnmounted(() => {
    window.removeEventListener("keydown", handleKeyDown);
    window.removeEventListener("keyup", handleKeyUp);
  });
};

useKeyboardEvent();

// 在组件挂载时初始化渲染
onMounted(() => {
  const width = window.innerWidth;
  const height = window.innerHeight;

  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(750, width / height, 0.1, 2000);
  renderer = new THREE.WebGLRenderer({ alpha: true });

  renderer.setSize(width, height);
  container.value.appendChild(renderer.domElement);
  const light = new THREE.AmbientLight(0x909090);
  scene.add(light);

  const loader = new MMDLoader();

  camera.position.z = cameraPosition.z;

  loader.load(
    "/qque/青雀（分桦）.pmx",
    function (mesh) {
      scene.add(mesh);
    },
    function (xhr) {
      console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
    },
    function (error) {
      console.log("An error happened");
    }
  );

  // 动画循环
  function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
  }

  animate();
});
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
</style>
